﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StoryCardManager : Singleton<StoryCardManager>
{
    private StoryCollection storyCollection;
    private Dictionary<string, CharacterStory> characterStories = new();  //存储角色与其对应的故事列表

    private void Awake()
    {
        LoadStoryCollection();
        InitializeCharacterStories();
    }

    #region 初始化与加载配置
    private void LoadStoryCollection()
    {
        TextAsset jsonFile = Resources.Load<TextAsset>("Stories");
        if (jsonFile != null)
        {
            storyCollection = JsonUtility.FromJson<StoryCollection>(jsonFile.text);
            Debug.Log($"故事配置加载成功！共 {storyCollection.stories.Count} 个角色");
        }
        else
        {
            Debug.LogError("故事配置文件加载失败！");
        }
    }

    private void InitializeCharacterStories()
    {
        characterStories.Clear();
        foreach (var story in storyCollection.stories)
        {
            if (!characterStories.ContainsKey(story.characterName))
                characterStories.Add(story.characterName, story);
        }
    }
    #endregion

    #region 外部接口

    public int GetCharacterCounts()
    {
        return characterStories.Count;
    }

    /// <summary>
    /// 获取所有故事卡（也是阶段二）角色列表
    /// </summary>
    /// <returns>角色列表</returns>
    public List<string> GetAllCharacterNames()
    {
        var list = new List<string>(characterStories.Keys);
        return new List<string>(characterStories.Keys);
    }

    /// <summary>
    /// 获取该角色的故事组
    /// </summary>
    /// <param name="name">角色名字</param>
    /// <returns>该角色故事组</returns>
    public CharacterStory GetCharacterStory(string name)
    {
        if (characterStories.TryGetValue(name, out var story))
            return story;

        Debug.LogError($"未找到角色：{name}");
        return null;
    }

    /// <summary>
    /// 获取故事组的卡片列表
    /// </summary>
    /// <param name="name">角色</param>
    /// <returns>当前故事卡片列表</returns>
    public List<CardStoryData> GetCardsForCharacter(string name)
    {
        var story = GetCharacterStory(name);
        return story != null ? story.cards : new List<CardStoryData>();
    }

    /// <summary>
    /// 获取当前卡片对应的出牌顺序
    /// </summary>
    /// <param name="cardName">卡名</param>
    /// <returns>出牌顺序</returns>
    public int GetCardOrderByName(string cardName)
    {
        foreach (var story in characterStories.Values)
        {
            var card = story.cards.Find(c => c.cardName == cardName);
            if (card != null)
                return card.order;
            //Debug.LogError($"未找到卡牌：{cardName}");
        }

        return -1;
    }

    #endregion
}
